$(function () {
    getCodeClass("kpiType", "kpiType");
    jeDate("#beginTimeQuery", {
        format: "YYYY-MM-DD"
    });
    jeDate("#endTimeQuery", {
        format: "YYYY-MM-DD"
    });
    query();
    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    jeDate("#beginTime", {
        format: "YYYY-MM",
        minDate: getSysDate(),
    });
    jeDate("#endTime", {
        format: "YYYY-MM-DD"
    });
    getSmsConfig("msgType", "hr");

    $(".js-add-save").unbind("click").click(function () {
        updateKpiPlan();
    });
    $("#kpiRule").unbind("change").change(function () {
        if ($(this).val() == "1") {
            $("#chargetr").show();
        } else {
            $("#chargetr").hide();
        }
    });
    $(".js-child-item").unbind("click").click(function () {
        addChildItem();
    });
    $("#kpiType").unbind("change").change(function () {
        getItemlist();
    });

})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/hrget/getMyHrKpiPlanList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        sortOrder: "asc",
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'planId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',//标题  可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'title',
            title: '计划标题',
            sortable: true,
            width: '150px',
            formatter:function (value,row,index)
            {
                return "<a href=\"javascript:void(0);details('" + row.planId + "')\" style='cursor: pointer'>"+value+"</a>";
            }
        }, {
            field: 'kpiRule',
            width: '50px',
            title: '考核规则',
            formatter: function (value, row, index) {
                if (value == "1") {
                    return "指定考核人";
                } else if (value = "2") {
                    return "部门主管考核";
                } else if (value == "3") {
                    return "逐级考核";
                }
            }
        }, {
            field: 'status',
            width: '50px',
            title: '当前状态',
            formatter: function (value, row, index) {
                if (value == "0") {
                    return "未生效";
                } else if (value == "1") {
                    return "生效中";
                } else if (value == "2") {
                    return "已终止";
                }
            }
        }, {
            field: 'beginTime',
            width: '50px',
            title: '开始日期'
        }, {
            field: 'endTime',
            width: '100px',
            title: '截止日期'
        }, {
            field: 'createTime',
            title: '创建时间',
            width: '100px'
        }, {
            field: 'createUser',
            title: '创建人',
            width: '100px',
            formatter: function (value, row, index) {
                return getUserNameByStr(value);
            }
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '120px',
            formatter: function (value, row, index) {
                return createOptBtn(row.planId, row.status);
            }
        }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list
                    //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        status: $("#statusQuery").val(),
        kpiRule: $("#kpiRuleQuery").val(),
        endTime: $("#endTimeQuery").val(),
        beginTime: $("#beginTimeQuery").val()
    };
    return temp;
};

function createOptBtn(planId, status) {
    var html = "";
    if (status == "0") {
        html += "<a href=\"javascript:void(0);edit('" + planId + "')\" class=\"btn btn-primary btn-xs\">编辑</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);updatePlanEffect('" + planId + "')\" class=\"btn btn-success btn-xs\">生效</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);deletePlan('" + planId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    } else if (status == "1") {
        html += "<a href=\"javascript:void(0);stopPlan('" + planId + "')\" class=\"btn btn-warning btn-xs\" >终止</a>";
    } else if (status == "2") {
        html += "<a href=\"javascript:void(0);edit('" + planId + "')\" class=\"btn btn-primary btn-xs\">编辑</a>"
    }
    return html;
}

function stopPlan(planId) {
    if (confirm("确定终止当前考核计划吗？")) {
        $.ajax({
            url: "/set/hrset/stopHrKpiPlan",
            type: "post",
            dataType: "json",
            data: {planId: planId},
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}

function deletePlan(planId) {
    if (confirm(sysmsg['OPT_CONFIRM_DELETE'])) {
        $.ajax({
            url: "/set/hrset/deleteHrKpiPlan",
            type: "post",
            dataType: "json",
            data: {planId: planId},
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}

function updatePlanEffect(planId) {
    if (confirm("您确定要生效吗？")) {
        $.ajax({
            url: "/set/hrset/updatePlanEffect",
            type: "post",
            dataType: "json",
            data: {planId: planId},
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}


function edit(planId) {
    getKpiItemList(planId);
    $("#planlistdiv").hide();
    $("#plandiv").show();
    $(".js-back-btn").unbind("click").click(function () {
        goback();
    })
    $("#chargeUser").attr("data-value","");
    $("#userPriv").attr("data-value","");
    $("#deptPriv").attr("data-value","");
    $("#levelPriv").attr("data-value","");
    $("#hrattach").attr("data_value","");
    $("#hrattach_show").empty();
    document.getElementById("form2").reset();
    $.ajax({
        url: "/ret/hrget/getHrKpiPlanById",
        type: "post",
        dataType: "json",
        data: {planId: planId},
        success: function (data) {
            if (data.status == "200") {
                var recordInfo = data.list;
                for (var id in recordInfo) {
                    if (id == "attach") {
                        $("#show_hrattach").html("");
                        $("#hrattach").attr("data_value", recordInfo.attach);
                        createAttach("hrattach", 4);
                    } else if (id == "chargeUser") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $("#" + id).val(getUserNameByStr(recordInfo[id]));
                    } else if (id == "userPriv") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $("#" + id).val(getUserNameByStr(recordInfo[id]));
                    } else if (id == "deptPriv") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $("#" + id).val(getDeptNameByStr(recordInfo[id]));
                    } else if (id == "levelPriv") {
                        $("#" + id).attr("data-value", recordInfo[id]);
                        $("#" + id).val(getHrUserLevelByStr(recordInfo[id]));
                    } else {
                        $("#" + id).val(recordInfo[id]);
                    }
                }
                $(".js-update-save").unbind("click").click(function () {
                    updateKpiPlan(planId);
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function details(planId) {
    window.open("/app/core/hr/kpiplandetails?planId=" + planId);
}


function getParam() {
    var paramArr = [];
    $("#child-item-table").find("tr").each(function () {
        var json = {};
        var sortNo = $(this).children("td").eq(0).find("input").val();
        var itemId = $(this).children("td").eq(1).attr("data-value");
        json.sortNo = sortNo;
        json.itemId = itemId;
        paramArr.push(json);
    });
    return JSON.stringify(paramArr);
}

function updateKpiPlan(planId) {
    if($("#title").val()=="")
    {
        layer.msg("标题不能为空!");
        return;
    }
    $.ajax({
        url: "/set/hrset/updateHrKpiPlan",
        type: "post",
        dataType: "json",
        data: {
            planId: planId,
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            beginTime: $("#beginTime").val(),
            endTime: $("#endTime").val(),
            chargeUser: $("#chargeUser").attr("data-value"),
            kpiRule: $("#kpiRule").val(),
            userPriv: $("#userPriv").attr("data-value"),
            deptPriv: $("#deptPriv").attr("data-value"),
            levelPriv: $("#levelPriv").attr("data-value"),
            msgType: getCheckBoxValue("msgType"),
            attach: $("#hrattach").attr("data_value"),
            remark: $("#remark").val(),
            itemList: getParam()
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function addChildItem() {
    $("#setkpiitemmodal").modal("show");
    $(".js-save").unbind("click").click(function () {
        var arr = getItemCheckBoxValue();
        for (var i = 0; i < arr.length; i++) {
            var index = $("#child-item-table").find("tr").length;
            $("#child-item-table").append("<tr><td><input type='number' name='sortNo' value='" + (index + 1) + "' class='form-control'></td>" +
                "<td data-value=\"" + arr[i].itemId + "\">" + arr[i].title + "</td><td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a></td></tr>");
        }
        $("#setkpiitemmodal").modal("hide");
    });
}

function deleteChildItem(Obj) {
    $(Obj).parent("td").parent("tr").remove();
}

function getKpiItemList(planId) {
    $("#child-item-table").empty();
    $.ajax({
        url: "/ret/hrget/getHrKpiPlanItemList",
        type: "post",
        dataType: "json",
        data: {planId: planId},
        success: function (data) {
            if (data.status == "200") {
                var arr = data.list;
                for (var i = 0; i < arr.length; i++) {
                    var index = $("#child-item-table").find("tr").length;
                    $("#child-item-table").append("<tr><td><input type='number' name='sortNo' value='" + arr[i].sortNo + "' class='form-control'></td>" +
                        "<td data-value=\"" + arr[i].itemId + "\">" + arr[i].title + "</td><td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a></td></tr>");
                }

            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }
        }
    });
}

function getItemlist() {
    $.ajax({
        url: "/ret/hrget/getHrKpiItemListForSelect",
        type: "post",
        dataType: "json",
        data: {kpiType: $("#kpiType").val()},
        success: function (data) {
            if (data.status == "200") {
                var itemInfo = data.list;
                var html = "";
                for (var i = 0; i < itemInfo.length; i++) {
                    html += "<div class=\"checkbox\"><label><input type=\"checkbox\" name=\"kpiitem\" data-title=\"" + itemInfo[i].title + "\" value=\"" + itemInfo[i].itemId + "\"><span class=\"text\">" + itemInfo[i].title + "</span></label></div>";
                }
                $(".itemlist").html(html);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function getItemCheckBoxValue() {
    var returnArr = [];
    $('input[name="kpiitem"]:checked').each(function () {
        var json = {};
        json.itemId = $(this).val();
        json.title = $(this).attr("data-title");
        returnArr.push(json);
    });
    return returnArr;
}

function goback() {
    $("#plandiv").hide();
    $("#planlistdiv").show();
}
